import Flutter
import UIKit

class ToFlutterPage: UIViewController {

    // FlutterViewController 实例，避免重复绑定
    private var flutterVC: FlutterViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        title = "原生页面"

        let button = UIButton(type: .system)
        button.setTitle("打开 Flutter 首页", for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        button.addTarget(self, action: #selector(openFlutterPage), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(button)

        let testButton = UIButton(type: .system)
        testButton.setTitle("打开 Flutter 测试页", for: .normal)
        testButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        testButton.addTarget(self, action: #selector(openFlutterTestPage), for: .touchUpInside)
        testButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(testButton)

        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            testButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            testButton.topAnchor.constraint(equalTo: button.bottomAnchor, constant: 20),
        ])
    }

    @objc private func openFlutterPage() {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        guard let flutterEngine = appDelegate.flutterEngine else {
            print("FlutterEngine 未初始化")
            return
        }

        if flutterVC == nil {
            flutterVC = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
            flutterVC?.modalPresentationStyle = .fullScreen
        }

        flutterEngine.viewController = nil
        if let vc = flutterVC {
            self.present(vc, animated: true, completion: nil)
        }
    }

    @objc private func openFlutterTestPage() {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        guard let flutterEngine = appDelegate.flutterEngine else {
            print("FlutterEngine 未初始化")
            return
        }

        flutterEngine.viewController = nil

        let testFlutterVC = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
        testFlutterVC.modalPresentationStyle = .fullScreen

        // 先展示 Flutter 页面，再通过 channel 通知 Dart 跳转
        self.present(testFlutterVC, animated: true) {
            let channel = FlutterMethodChannel(
                name: "com.eason.nebula/navigation", binaryMessenger: flutterEngine.binaryMessenger)
            channel.invokeMethod("goToPage", arguments: "settings")
        }
    }
}
